package com.data.wms.test;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ant-Man
 * @Date: 2021/1/28 16:38
 */
public class Itest {

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("/Users/kangkang/Desktop/req.json");

        FileInputStream in = new FileInputStream(file);

        try {
            InputStreamReader inputReader = new InputStreamReader(new FileInputStream(file));
            BufferedReader bf = new BufferedReader(inputReader);
            // 按行读取字符串
            String str;
            while ((str = bf.readLine()) != null) {
                System.out.println("当前数据：" + str);
                Map<String, String> header = Maps.newHashMap();
                header.put("X-API_TOKEN", "2b41b2de614511ebb6f1525400742875");
                post("https://api.mzdata.top/data-dist/api/dist/stock/skuOutput", str, header);
                Thread.sleep(1000);
            }
            bf.close();
            inputReader.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String post(String url, String param, Map<String, String> header) {
        HttpPost httpPost = new HttpPost(url);
        header.forEach(httpPost::addHeader);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

        StringEntity entity = new StringEntity(param, Charset.defaultCharset());
        httpPost.setEntity(entity);
        HttpResponse result;
        CloseableHttpClient httpClient = httpClient();
        try {
            result = httpClient.execute(httpPost);
            return EntityUtils.toString(result.getEntity());
        }
        catch (IOException e) {
            throw new RuntimeException("HTTP请求异常", e);
        }
        finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.fillInStackTrace();
            }
        }
    }

    private static CloseableHttpClient httpClient() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();

        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }

}
